<template>
	<el-dialog title="邀请好友" :visible.sync="visible" width="50%" :before-close="onClose">
		<div class="agm-container">
			<div class="agm-l-box">
				<el-input placeholder="搜索好友" v-model="searchText"
					@keyup.enter.native="onSearch()">
					<i class="el-icon-search el-input__icon" slot="suffix"> </i>
				</el-input>
				<el-scrollbar style="height:400px;">
					<!--<div v-for="(friend,index) in friends" :key="friend.id">
						<friend-item v-show="friend.nickName.startsWith(searchText)" :showDelete="false"
							@click.native="onSwitchCheck(friend)" :menu="false" :friend="friend" :index="index"
							:active="false">
							<el-checkbox :disabled="friend.disabled" @click.native.stop="" class="agm-friend-checkbox"
								v-model="friend.isCheck" size="medium"></el-checkbox>
						</friend-item>
					</div>-->


                    <el-tree
                            :data="leftArr"
                            :props="defaultProps"
                            ref="leftTree"
                            :filter-node-method="filterNodeFrom"
                            @node-click="handleNodeClick"
                    >
                        <span slot-scope="{ node, data }" :style="{ display: 'inline-block'}">

                            <span v-show="data.userFlag == 0" >{{ data.nickName}}</span>
                            <friend-item v-show="data.userFlag == 1" :index="data.id" :data-item="data" :showDelete="false"
                                     :active="false"  @click.native="onSwitchCheck(data)">
                                <!--<el-checkbox :disabled="data.disabled" @click.native.stop="" class="agm-friend-checkbox"
                                             v-model="data.isCheck" size="mini"></el-checkbox>-->
					        </friend-item>
                        </span>
                    </el-tree>

				</el-scrollbar>
			</div>
			<div class="agm-arrow el-icon-d-arrow-right"></div>
			<div class="agm-r-box">
				<div class="agm-select-tip"> 已勾选{{checkCount}}位好友</div>
				<el-scrollbar style="height:400px;">
					<!--<div v-for="(friend,index) in friends" :key="friend.id">
						<friend-item v-if="friend.isCheck && !friend.disabled" :friend="friend" :index="index"
							:active="false" @del="onRemoveFriend(friend,index)" :menu="false">
						</friend-item>
					</div>-->

                    <el-tree
                            :data="rightArr"
                            :props="defaultProps"
                            ref="rightTree"
                    >
                        <span slot-scope="{ node, data }" :style="{ display: 'inline-block'}">

                            <span v-show="data.userFlag == 0" >{{ data.nickName}}</span>
                            <!--<friend-item v-show=" 'headImage' in data && data.isCheck && !data.disabled" :data-item="data" :index="data.id"
                                         :active="false" @del="onRemoveFriend(data,index)" :menu="false">{{'headImage' in data}}
						    </friend-item>-->
                            <friend-item v-show=" data.userFlag == 1  " :index="data.id" :data-item="data"
                                         :active="false" @del="onRemoveFriend(data,index)" :menu="false">
					        </friend-item>
                        </span>
                    </el-tree>


				</el-scrollbar>
			</div>
		</div>
		<span slot="footer" class="dialog-footer">
			<el-button @click="onClose()">取 消</el-button>
			<el-button type="primary" @click="onOk()">确 定</el-button>
		</span>
	</el-dialog>
</template>

<script>
	import FriendItem from '../friend/FriendItem.vue';

	export default {
		name: "addGroupMember",
		components: {
			FriendItem
		},
		data() {
			return {
				searchText: "",
				friends: [],
                defaultProps: {
                    children: "children",
                    label: "nickName"
                },
                leftArr: [],
                rightArr:[]
            }
		},
		methods: {
            // 左侧树筛选
            filterNodeFrom(value, data) {
                if (this.filterNode) {
                    return this.filterNode(value, data, "form");
                }
                if (!value) return true;
                return data[this.defaultProps.label].indexOf(value) !== -1;
            },
            handleNodeClick(friend,node) {
                console.log(" ------->data : " + JSON.stringify(friend));
                console.log(" ------->node : "+node)

                /*console.log("=======1======="+JSON.stringify(friend))
                if (!friend.disabled) {
                    console.log("------------------------------")
                    friend.isCheck = !friend.isCheck
                }
                console.log("树形数据结构："+JSON.stringify(this.$store.state.friendStore.friends))*/

            },
			onClose() {
				this.$emit("close");
			},
			onOk() {

                //alert(JSON.stringify(this.rightArr))
				let inviteVO = {
					groupId: this.groupId,
					friendIds: []
				}
				this.rightArr.forEach((f) => {
					if (f.isCheck ) {
						inviteVO.friendIds.push(f.id);
					}
				})
                //alert(JSON.stringify(inviteVO))
				if (inviteVO.friendIds.length > 0) {
					this.$http({
						url: "/group/invite",
						method: 'post',
						data: inviteVO
					}).then(() => {
						this.$message.success("邀请成功");
						this.$emit("reload");
						this.$emit("close");
					})
				}
			},
			onRemoveFriend(friend, index) {
				friend.isCheck = false;
			},
			onSwitchCheck(friend) {
                console.log("======111111=1======="+JSON.stringify(friend))
				if (!friend.disabled) {
                    console.log("------------------------------")
                    friend.isCheck = !friend.isCheck
				}
                if (!this.rightArr.some(node => node.id === friend.id)) {
                    // 如果节点不存在，则添加到右侧树中
                    this.rightArr.push(friend);
                }
                if (this.rightArr.some(node => node.id === friend.id) && !friend.isCheck ) {
                    // 如果节点存在，则从右侧树中删除
                    console.log("------------0000000000000000------------------")
                    this.rightArr = this.rightArr.filter(obj => obj !== friend);
                }
            },
            factorial(arr, friends) {
                //迭代
                arr.forEach(n => {
                    //forEach循环
                    let f = JSON.stringify(n)
                    console.log("33==================="+f);
                    if ( f.includes('children')  ) {
                        let newStr = n.children;
                        return this.factorial(newStr,friends)
                    }else{
                        let friend = n
                        let m = this.members.filter((m) => !m.quit)
                            .find((m) => m.userId == friend.id);
                        if (m) {
                            // 好友已经在群里
                            friend.disabled = true;
                            friend.isCheck = true
                        } else {
                            friend.disabled = false;
                            friend.isCheck = false;
                        }
                        //this.friends.push(friend);
                    }
                })
            }
		},
		props: {
			visible: {
				type: Boolean
			},
			groupId: {
				type: Number
			},
			members: {
				type: Array
			}
		},
		computed: {
			checkCount() {
				return this.rightArr.length;
			}
		},
		watch: {
			visible: function(newData, oldData) {
				if (newData) {
					this.friends = []
                    this.leftArr = this.$store.state.friendStore.friends
					/*this.$store.state.friendStore.friends.forEach((f) => {
					    alert(JSON.stringify(f))
						let friend = JSON.parse(JSON.stringify(f))
						let m = this.members.filter((m) => !m.quit)
							.find((m) => m.userId == f.id);
						if (m) {
							// 好友已经在群里
							friend.disabled = true;
							friend.isCheck = true
						} else {
							friend.disabled = false;
							friend.isCheck = false;
						}
						this.friends.push(friend);
					})*/

                    //迭代树形结构,叶子节点添加disabled 、isCheck 树形
                    this.factorial(this.leftArr,this.friends)
                    console.log(">>>>>>>"+JSON.stringify(this.leftArr))

				}
			},
            searchText(val){
                //console.log("============>>>>>>>"+this.$refs["leftTree"].toArray())
                console.log("============>>>>>>>"+this.$refs["leftTree"].filter(val))
                this.$refs["leftTree"].filter(val);
            },
		}

	}
</script>

<style lang="scss">
	.agm-container {
		display: flex;
		.agm-l-box {
			flex: 1;
			border: #587FF0 solid 1px;
			border-radius: 5px;
			overflow: hidden;

			.el-checkbox {
				display: flex;
				align-items: center;

				//修改选中框的大小
				.el-checkbox__inner {
					width: 20px;
					height: 20px;

					//修改选中框中的对勾的大小和位置
					&::after {
						height: 12px;
						left: 7px;
					}
				}

				//修改点击文字颜色不变
				.el-checkbox__input.is-checked+.el-checkbox__label {
					color: #333333;
				}

				.el-checkbox__label {
					line-height: 20px;
					padding-left: 8px;
				}
			}

			.agm-friend-checkbox {
				margin-right: 20px;
			}
		}

		.agm-arrow {
			display: flex;
			align-items: center;
			font-size: 20px;
			padding: 10px;
			font-weight: 600;
			color: #687Ff0;
		}

		.agm-r-box {
			flex: 1;
			border: #587FF0 solid 1px;
			border-radius: 5px;

			.agm-select-tip {
				text-align: left;
				height: 40px;
				line-height: 40px;
				text-indent: 5px;
			}
		}
	}
</style>
